const { execSync } = require('child_process');

const getMatchRowNumber = (match, filePath) => {
  const stdout = execSync(`grep -n "${match}" "${filePath}"`).toString();

  return stdout.split('\n').map((str) => str.split(':')[0]);
};

const insertInLineNo = (lineNumber = 0, text = '', filePath) => {
  const s = text.replace(/"/g, "'");
  const tempFile = `${filePath}.new`;
  // console.log('s\n', s);
  const u = `awk -v n=${lineNumber} -v s="${s}" 'NR == n {print s} {print}' ${filePath} > ${tempFile}`;
  const stdout = execSync(u).toString();
  execSync(`cp ${tempFile} ${filePath}`);
  execSync(`rm ${tempFile}`);
  return stdout;
};

module.exports = {
  getMatchRowNumber,
  insertInLineNo,
};

// let count = 0;

// fs.createReadStream('./test.cpp')
//   .on('data', (chunk) => {
//     for (let i = 0; i < chunk.length; i += 1) {
//       if (chunk[i] === 10) count += 1;
//     }
//   })
//   .on('end', () => {
//     console.log(count);
//   });
